package com.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author MingCha Yang
 * 登录过滤器
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String requestURI = req.getRequestURI();//  如/idea-ssm/jsp/Article/article-add.jsp
        String contextPath = req.getContextPath();// 如/idea-ssm
        HttpSession session = req.getSession();// 获取一个session对象
        //第一个参数和子串的起点一样，第二个参数比子串的终点大1
        String targURI = requestURI.substring(contextPath.length(), requestURI.length());
        if("/jsp/login.jsp".equals(targURI)){
            chain.doFilter(req,resp);
            return;
        }else {
            if("/".equals(targURI)){
                return;
            }else{
                if(session.getAttribute("user_session") == null){
                    resp.sendRedirect(contextPath+"/jsp/login.jsp");
                    return;
                }else {
                    chain.doFilter(req,resp);
                    return;
                }
            }
        }


    }

    @Override
    public void destroy() {

    }
}
